package ASCENSOR;
/**
 * Aca se definen e implementan las funciones que utiliza la interfaz grafica 
 */
import gnu.io.*;
/*
 import gnu.io.CommPort;
 import gnu.io.CommPortIdentifier;
 import gnu.io.PortInUseException;
 import gnu.io.SerialPort;
 */
import java.util.*;

import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.awt.Color;
//import java.util.HashSet;


public class TwoWaySerialComm 
{
	public TwoWaySerialComm()
	{
		super();

	}

	// PUERTO QUE SE VA A ABRIR
	private static final String PORT_NAMES[] = { "/dev/ttyUSB0",
			"/dev/ttyUSB1", "/dev/ttyUSB2", "/dev/ttyUSB3", };
	
	static OutputStream       outputStream;
   // static String	      messageString = "ON01";
    
    static SerialPort  PUERTOCERRAR;
    static SerialPort  serialPort;
    
//    static Enumeration	      portList;
    static CommPortIdentifier portId;
    static CommPortIdentifier portIdentifier;
//    static CommPort	commPort;
    
	static String defaultPort = "/dev/ttyUSB1";
/**
 * @param portName
 * @throws Exception
 * Abre el puerto e inicializa a 9600, 8 bits, 1 bit de parada, sin paridad.
 * 
 */
	static void connect(String portName) throws Exception
	{
		/*CommPortIdentifier portIdentifier = CommPortIdentifier
				.getPortIdentifier(portName);//*/
		portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
		
		if (portIdentifier.isCurrentlyOwned())
		{
			System.out.println("Error: Port is currently in use");
		} else
		{
			/*CommPort commPort = portIdentifier.open(this.getClass().getName(),
					2000); //*/
			CommPort commPort = portIdentifier.open("SimpleWrite",2000);
			//commPort = portIdentifier.open("SimpleWrite",2000);
			if (commPort instanceof SerialPort)
			{
				//SerialPort serialPort = (SerialPort) commPort;
				serialPort = (SerialPort) commPort;
				/*serialPort = 
					    (SerialPort) portIdentifier.open("SimpleWrite", 2000);//*/
				 
				
				try {
						outputStream = serialPort.getOutputStream();
					    } catch (IOException e) {}
				
				serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
						SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

				InputStream in = serialPort.getInputStream();
				OutputStream out = serialPort.getOutputStream();

				/*(new Thread(new SerialReader(in))).start();
				(new Thread(new SerialWriter(out))).start();//*/
				
				try 
			    {
			    	serialPort.notifyOnOutputEmpty(true);
			    } catch (Exception e) {
				System.out.println("Error setting event notification");
				System.out.println(e.toString());
				System.exit(-1);
			    }
				
			} else
			{
				System.out
						.println("Error: Only serial ports are handled by this example.");
			} 
			System.out.println("puerto Abierto " + defaultPort);
		}
	}
	
	/**
	 * cierra el puerto 
	 * 
	 * @param portName
	 * @throws Exception
	 */
		//public static void CerrarPuerto(String portName) throws Exception
		public static void CerrarPuerto() throws Exception
		{
			//defaultPort = portName;
			System.out.println("Tratando de cerrar el puerto");
		//	portList = CommPortIdentifier.getPortIdentifiers();
			portId = portIdentifier;

			    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) 
			    {
				    System.out.println("Found port " + portId.getName());
				    PUERTOCERRAR = serialPort;
				    
				    try {
					outputStream = PUERTOCERRAR.getOutputStream();
				    } catch (IOException e) 
				    {
				    	System.out.println("EROR");
				    }
/*
				    try 
				    {
				    	PUERTOCERRAR.setSerialPortParams(9600, 
								       SerialPort.DATABITS_8, 
								       SerialPort.STOPBITS_1, 
								       SerialPort.PARITY_NONE);
				    } catch (UnsupportedCommOperationException e) {}
			
//*/
				    try 
				    {
				    	PUERTOCERRAR.notifyOnOutputEmpty(true);
				    } catch (Exception e) {
					System.out.println("Error setting event notification");
					System.out.println(e.toString());
					System.exit(-1);
				    }

				    try {
				       Thread.sleep(2000);  // Be sure data is xferred before closing
				    } catch (Exception e) {}
				    System.out.println("PUERTO CERRADO");
				    PUERTOCERRAR.close();
				    System.exit(1);

			    } 

			
			
		}
	
	
	
	/** LECTURA DE LO QUE ENTRA AL PUERTO USB */
/*	public static class SerialReader implements Runnable
	{
		InputStream in;

		public SerialReader(InputStream in)
		{
			this.in = in;
		}

		public void run()
		{
			byte[] buffer = new byte[1024];
			int len = -1;
			try
			{
				while ((len = this.in.read(buffer)) > -1)
				{
					System.out.print(new String(buffer, 0, len));
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}

	/** ESCRITURA EN EL PUERTO USB */
/*	public static class SerialWriter implements Runnable
	{
		OutputStream out;

		public SerialWriter(OutputStream out)
		{
			this.out = out;
		}

		public void run()
		{
			try
			{
				int c = 0;
				while ((c = System.in.read()) > -1)
				{
					this.out.write(c);
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}//*/
	/** Funcion que escribe una cadena en el puerto
	 * 
	 * 
	 */
	public static void EscribirPuerto( String messageString)
	{
		try
		{
			outputStream.write(messageString.getBytes());
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

	/**
	 * @return A HashSet containing the CommPortIdentifier for all serial ports
	 *         that are not currently being used.
	 *         Obtiene todos los puertos disponible
	 */
	public static HashSet<CommPortIdentifier> getAvailableSerialPorts()
	{
		HashSet<CommPortIdentifier> h = new HashSet<CommPortIdentifier>();
		Enumeration thePorts = CommPortIdentifier.getPortIdentifiers();
		while (thePorts.hasMoreElements())
		{
			CommPortIdentifier com = (CommPortIdentifier) thePorts
					.nextElement();

			for (String portName : PORT_NAMES)
			{

				if (com.getName().equals(portName))
				{	
					defaultPort = com.getName();
					System.out.println("puerto Encontrado " + defaultPort);
				}

			}

		
		}
		return h;  //verificar si no esta de mas!
		
	}

	
	

	/**
	 * Main de ejecucion
	 * @throws InterruptedException 
	 * */
	public static void main() throws InterruptedException
	{
		//
		TwoWaySerialComm main = new TwoWaySerialComm();
	}
		
}